package com.keyue.common.utils;

import com.keyue.config.AliOssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.LocalDateTime;

/**
 * @author: xms
 * @description: TODO
 * @date: 2023/12/13 16:04
 * @version: 1.0
 */

@Slf4j
@Service
public class DbUtil {

    /**
     * 备份数据库
     *
     * @param ip
     * @param port
     * @param username
     * @param password
     * @param databaseName
     * @param savePath
     * @param fileName
     */
    public void exportDatabaseTool(String ip, String port, String username, String password, String databaseName, String savePath, String fileName) {
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            String cmd1 = "/bin/sh";
            String cmd2 = "-c";
            String os_name = System.getProperty("os.name");
            // 判断是否是windows系统
            if (os_name.toLowerCase().startsWith("win")) {
                cmd1 = "cmd";
                cmd2 = "/c";
            }
            File saveFile = new File(savePath);
            if (!saveFile.exists()) {
                // 目录不存在创建新的文件夹
                saveFile.mkdirs();
            }
            if (!savePath.endsWith(File.separator)) {
                savePath = savePath + File.separator;
            }
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf-8"));
            String stmt2 = "mysqldump -h" + ip + " -p" + port + " -u" + username + " -p" + password + " --default-character-set=utf8 " + databaseName;
            String[] cmd = {cmd1, cmd2, stmt2};
            Process process = Runtime.getRuntime().exec(cmd);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            AliOssUtil.upload(AliOssConfig.ALIYUN_BUCKET, fileName, FileUtil.imageParseBytes(process.getInputStream()));
            log.info("已备份数据库,日期:{}", DateUtils.format(LocalDateTime.now(), DateUtils.DATE_TIME));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("备份数据库失败,日期:{},e:{}", DateUtils.format(LocalDateTime.now(), DateUtils.DATE_TIME), e.toString());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
